package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {
    private static DataSource dataSource;

    static {
        try {
        Properties p = new Properties();
        InputStream res = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            p.load(res);
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("未获取到数据源");
        }

    }

    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("未获取到连接");
            return null;
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }

    public static void close(Connection con, Statement stat) {
        try {
            if(stat != null) stat.close();
            if(con != null) con.close();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("释放资源报错");
        }
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet) {
        if(con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("释放资源报错");
            }
        }
    }
}
